package cn.edu.seu.ssny.socket;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.apache.commons.lang3.StringUtils;

import java.util.logging.Level;
import java.util.logging.Logger;


@Sharable
public class MyServerHandler extends ChannelHandlerAdapter {
    private StringBuffer sb = new StringBuffer();

    private final Logger logger = Logger.getLogger(MyServerHandler.class.getName());

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接完成");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        sb.append(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        String context = sb.toString();
        sb.setLength(0);
        String keyword = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        int num = StringUtils.countMatches(context, keyword);
        while (num-- != 0) {
            String body = keyword + StringUtils.substringAfterLast(context, keyword);
            context = StringUtils.substringBeforeLast(context, keyword);
            try {
                XMLHandler.handler(body);
            } catch (Exception e) {
                logger.log(Level.WARNING, "发生错误，关闭链接。", e);
                ctx.close();
            }
        }
        ctx.flush();
        ctx.close();
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) {
        logger.log(Level.WARNING, "关闭链接。");
        ctx.close(promise);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.log(Level.WARNING, "发生错误，关闭链接。", cause);
        ctx.close();
    }
}